package com.github.linkoog.model_designer.common;

import com.intellij.openapi.util.Couple;
import com.intellij.util.ui.UIUtil;

import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import java.awt.*;

public class JCheckBoxTableCellRenderer extends JCheckBox implements TableCellRenderer {

    private final JPanel myPanel = new JPanel();

    private boolean ignoreCellValue = false;

    public JCheckBoxTableCellRenderer() {
        this(CENTER,null, null);
    }

    public JCheckBoxTableCellRenderer(final String text) {
        this(CENTER,null, text);
    }


    public JCheckBoxTableCellRenderer(final int horizontalAlignment,final Icon icon, final String text) {
        super();
        setIcon(icon);
        setText(text);
        setHorizontalAlignment(horizontalAlignment);
        setVerticalAlignment(CENTER);
        setBorderPainted(true);
        setBorder(null);
        setOpaque(true);
        myPanel.setOpaque(true);
    }

    public void setIgnoreCellValue(boolean ignoreCellValue) {
        this.ignoreCellValue = ignoreCellValue;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSel, boolean hasFocus, int row, int column) {
        Couple<Color> colors = UIUtil.getCellColors(table, isSel, row, column);
        setOpaque(true);
        if (value == null) {
            myPanel.setBackground(colors.getSecond());
            return myPanel;
        }

        setForeground(colors.getFirst());
        setBackground(colors.getSecond());

        if (! ignoreCellValue){
            if (value instanceof String) {
                setSelected(Boolean.parseBoolean((String)value));
            } else {
                setSelected(((Boolean)value).booleanValue());
            }
        }
        setEnabled(table.isCellEditable(row, column));
        return this;
    }
}
